<template>
  <div>
    <div>
      <el-dialog
        title="用户信息"
        :visible.sync="userInfoDialogVisible"
        width="30%"
      >
        <div class="user-info-container">
          <div class="avator">
            <img :src="userInfo.avator" alt="" />
          </div>
          <div class="user-details">
            <div class="user-detail">
              <label>用户名:</label>
              <span>{{ userInfo.username }}</span>
            </div>
            <div class="user-detail">
              <label>手机号:</label>
              <span>{{ userInfo.phone }}</span>
            </div>
            <div class="user-detail">
              <label>邮箱:</label>
              <span>{{ userInfo.email }}</span>
            </div>
            <div class="user-detail">
              <label>注册时间:</label>
              <span>
                {{ userInfo.createTime[0] }}年{{ userInfo.createTime[1] }}月{{
                  userInfo.createTime[2]
                }}日
              </span>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <div>
      <i class="el-icon-search">搜索</i>
      <el-input
        v-model="userpage.content"
        placeholder="请输入关键词"
        style="width: auto"
      ></el-input>
      <el-button type="primary" plain style="left: 200px" @click="addUser"
        >添加用户</el-button
      >
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="编号" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" align="center">
          <template slot-scope="scope">
            <div slot="reference">
              <el-tag size="medium">{{ scope.row.username }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.sex }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="role"
          label="角色"
          width="100"
          :filters="getRoleFilters()"
          :filter-method="filterTag"
          filter-placement="bottom-end"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getHighestRoleColor(scope.row.role)"
              close-transition
              >{{ getHighestRole(scope.row.role) }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              :type="getActionButtonType(scope.row.role)"
              @click="handleDeleteOrCheck(scope.$index, scope.row)"
            >
              {{ getActionButtonText(scope.row.role) }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userpage.currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userpage.total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input
                type="password"
                v-model="ruleForm.password"
                auto-complete="new-password"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input
                type="password"
                v-model="ruleForm.checkPass"
                auto-complete="new-password"
              ></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="ruleForm.sex" placeholder="选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-checkbox-group
                v-model="ruleForm.role"
                @change="handleRoleChange"
              >
                <el-checkbox label="采编人员" name="1"></el-checkbox>
                <el-checkbox label="审核人员" name="2"></el-checkbox>
                <el-checkbox label="管理员" name="3"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>

    <div>
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="30%"
        :before-close="handleCloseAddUser"
      >
        <!-- 添加用户表单 -->
        <div>
          <el-form
            :model="addUserForm"
            :rules="rules1"
            ref="addUserForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <!-- ...（添加用户表单项）... -->
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="addUserForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input
                type="password"
                v-model="addUserForm.password"
                auto-complete="new-password"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input
                type="password"
                v-model="addUserForm.checkPass"
                auto-complete="new-password"
              ></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-select v-model="addUserForm.sex" placeholder="选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="role">
              <el-checkbox-group
                v-model="addUserForm.role"
                @change="handleRoleChange"
              >
                <el-checkbox label="采编人员" name="1"></el-checkbox>
                <el-checkbox label="审核人员" name="2"></el-checkbox>
                <el-checkbox label="管理员" name="3"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancleAddUser">取 消</el-button>
          <el-button @click="resetForm1('addUserForm')">重置</el-button>
          <el-button type="primary" @click="submitForm1('addUserForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
/* Adjust styling as needed */
.user-info-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0; /* 消除margin间距 */
}

.avator {
  margin-bottom: 25px;
  margin-right: 99px; /* 调整avator和其他内容的间距 */
}

.avator img {
  width: 100px;
  height: 100px;
}

/* 如果需要保持文字的垂直居中，可以添加下面的样式 */
.user-info-container div {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.user-details {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.user-detail {
  margin-left: 0;
  margin-bottom: 10px;
}

.user-detail label {
  font-weight: bold;
  margin-right: 5px;
}
</style>
<script>
import { getUsers, updateUser, deleteUser, addUser } from '@api/admin.js'

export default {
  name: 'UserInfo',
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePass3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addUserForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      content: '',
      userInfoDialogVisible: false,
      tableData: [],
      userpage: {
        total: 0,
        page: 1,
        size: 5,
        content: '',
        currentPage: 1
      },
      userInfo: {
        id: '',
        avator: '',
        username: '',
        email: '',
        phone: '',
        sex: '',
        createTime: ''
      },
      addDialogVisible: false,
      dialogVisible: false,
      // 定义角色颜色映射表
      roleColors: {
        管理员: 'danger',
        审核人员: 'warning',
        采编人员: 'success',
        普通用户: 'info'
      },
      addUserForm: {
        id: '',
        username: '',
        email: '',
        password: '',
        checkPass: '',
        phone: '',
        sex: '',
        role: [],
        index: ''
      },
      ruleForm: {
        id: '',
        username: '',
        email: '',
        password: '',
        checkPass: '',
        phone: '',
        sex: '',
        role: [],
        index: ''
      },
      rules: {
        name: [{ required: true, message: '用户名', trigger: 'blur' }],
        type: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'change'
          }
        ],
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern:
              /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        sex: [{ required: true, message: '请确认性别', trigger: 'change' }],
        role: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个角色',
            trigger: 'change'
          },
          {
            validator: this.validateRole,
            message: '只能选择一个角色',
            trigger: 'change'
          }
        ]
      },
      rules1: {
        name: [{ required: true, message: '用户名', trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass3, trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern:
              /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        sex: [{ required: true, message: '请确认性别', trigger: 'change' }],
        role: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个角色',
            trigger: 'change'
          },
          {
            validator: this.validateRole,
            message: '只能选择一个角色',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    'userpage.content' (newVal) {
      this.handleGetUsers()
      this.$forceUpdate()
    }
  },
  created () {
    this.handleGetUsers()
  },
  methods: {
    handleCloseAddUser () {
      this.addDialogVisible = false
      this.resetForm1('addUserForm')
    },
    cancleAddUser () {
      this.addDialogVisible = false
      this.resetForm1('addUserForm')
    },
    addUser () {
      // this.$refs['addUserForm'].resetFields()
      this.addDialogVisible = true
      this.addUserForm = {
        id: '',
        username: '',
        email: '',
        password: '',
        checkPass: '',
        phone: '',
        sex: '',
        role: [],
        index: ''
      }
      // 首先要删除已有的才是新增
      // Object.getOwnPropertyNames(this.addUserForm).forEach((key) => {
      //   delete this.addUserForm[key]
      // })
    },
    handleRoleChange () {
      // You can perform additional actions on role change if needed
    },
    validateRole (rule, value, callback) {
      if (value.length !== 1) {
        callback(new Error('请只选择一个角色'))
      } else {
        callback()
      }
    },
    getActionButtonType (role) {
      return role.includes('普通用户') ? 'success' : 'danger'
    },
    // 根据角色判断按钮文本
    getActionButtonText (role) {
      return role.includes('普通用户') ? '查看' : '删除'
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    handleEdit (index, row) {
      if (row.role.includes('普通用户')) {
        this.$message({
          message: '普通用户仅可查看',
          type: 'warning',
          duration: 1500
        })
        return
      }
      this.dialogVisible = true
      this.ruleForm.index = index
      // 遍历row的键
      Object.keys(row).forEach((key) => {
        // 判断ruleForm是否有相应的键，以避免赋值不存在的属性
        if (this.ruleForm.hasOwnProperty(key)) {
          // 将row的值赋给ruleForm
          this.ruleForm[key] = row[key]
        }
      })
      this.ruleForm.checkPass = row.password
      // console.log(this.ruleForm)
    },
    handleDeleteOrCheck (index, row) {
      // 在这里实现删除或查看的逻辑
      if (row.role.includes('普通用户')) {
        // 处理查看操作
        // console.log('查看操作', row)
        this.userInfoDialogVisible = true
        this.userInfo = row
        console.log(this.userInfo)
      } else {
        // 处理删除操作
        // console.log('删除操作', row)
        deleteUser(row.id).then((res) => {
          if (res.status) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500
            })
            this.handleGetUsers()
          } else {
            this.$message({
              message: '删除失败',
              type: 'error',
              duration: 1500
            })
          }
        })
      }
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.userpage.size = val
      this.handleGetUsers()
    },
    handleCurrentChange (val) {
      this.userpage.currentPage = val
      this.userpage.page = val
      console.log(`当前页: ${val}`)
      this.handleGetUsers()
    },
    async handleGetUsers () {
      const page = {
        content: this.userpage.content,
        page: this.userpage.page,
        size: this.userpage.size
      }
      await getUsers(page).then((res) => {
        this.tableData = res.data.items
        this.userpage.total = res.data.total
        console.log(this.tableData)
      })
    },

    getHighestRole (roles) {
      // 根据 roleColors 中的顺序，找到最高级别的角色
      const highestRole = Object.keys(this.roleColors).find((role) =>
        roles.includes(role)
      )
      return highestRole || ''
    },

    getHighestRoleColor (roles) {
      // 根据角色找到对应的颜色
      const role = this.getHighestRole(roles)
      return this.roleColors[role] || ''
    },
    getRoleFilters () {
      const allRoles = this.tableData.flatMap((item) => item.role) // 获取所有角色
      const uniqueRoles = Array.from(new Set(allRoles)) // 去重
      return uniqueRoles.map((role) => ({ text: role, value: role }))
    },

    filterTag (value, row) {
      return row.role.includes(value)
    },
    remoteMethod (query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options4 = this.list.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options4 = []
      }
    },
    submitForm (formName) {
      // this.dialogVisible = false
      this.$refs[formName].validate((valid) => {
        console.log('查看内容' + this.ruleForm.role)
        if (valid) {
          updateUser(this.ruleForm).then((res) => {
            console.log(res)
            if (res.status) {
              this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1500
              })
              this.dialogVisible = false
              this.handleGetUsers()
            } else {
              this.$message({
                message: '操作失败',
                type: 'error',
                duration: 1500
              })
            }
          })
          // 提交修改后的信息
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.ruleForm = this.tableData[this.ruleForm.index]
      this.ruleForm.checkPass = this.ruleForm.password
      // this.$refs[formName].resetFields()
    },
    resetForm1 (formName) {
      this.$refs[formName].resetFields()
    },
    submitForm1 (formName) {
      // this.dialogVisible = false
      this.$refs[formName].validate((valid) => {
        console.log('查看内容' + this.addUserForm.role)
        if (valid) {
          // 提交修改后的信息
          addUser(this.addUserForm).then((res) => {
            if (res.status) {
              this.$message({
                message: '添加成功',
                type: 'success',
                duration: 1500
              })
              this.addDialogVisible = false
              this.handleGetUsers()
            } else {
              this.$message({
                message: res.message,
                type: 'error',
                duration: 1500
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
